import { useRef, useMemo } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import useGameStore from '../context/gameStore';
import audioAnalyzerService from '../services/audioAnalyzerService';

// 根据音符类型获取颜色
const getColorByKey = (key) => {
  switch (key) {
    case 'q': return 'red';
    case 'w': return 'green';
    case 'e': return 'blue';
    case 'r': return 'purple';
    case 'space': return 'gold';
    default: return 'white';
  }
};

// 获取音符在x轴上的位置
const getLanePosition = (lane) => {
  const lanePositions = [-6, -2, 2, 6];
  return lanePositions[lane] || 0;
};

const Note = ({ note }) => {
  const meshRef = useRef();
  const materialRef = useRef();
  const gameStatus = useGameStore(state => state.gameStatus);
  const hitNotes = useGameStore(state => state.hitNotes);
  
  // 判断音符是否已被击中
  const isHit = useMemo(() => {
    return hitNotes.includes(note);
  }, [hitNotes, note]);
  
  // 音符颜色
  const color = getColorByKey(note.key);
  
  // 音符的X坐标 (根据轨道)
  const xPosition = getLanePosition(note.lane);
  
  // 长音符特殊处理
  const isLongNote = note.isLongNote;
  const noteWidth = isLongNote ? 16 : 1.5;
  const noteLength = isLongNote ? note.duration * 20 : 1;
  
  // 音符动画
  useFrame(() => {
    if (!meshRef.current || gameStatus !== 'playing') return;
    
    // 获取当前音乐播放时间
    const currentTime = audioAnalyzerService.currentTime;
    
    // 计算音符的Z位置 (基于时间差)
    // 音符从远处(-50)向玩家(0)移动
    const timeDistance = note.time - currentTime;
    const zPosition = -timeDistance * 20; // 速度系数
    
    meshRef.current.position.z = zPosition;
    
    // 如果音符已经被击中，应用特效
    if (isHit) {
      if (materialRef.current) {
        // 让已击中的音符逐渐淡出
        materialRef.current.opacity -= 0.05;
        materialRef.current.emissiveIntensity += 0.1;
        meshRef.current.scale.multiplyScalar(1.03);
        
        if (materialRef.current.opacity <= 0) {
          // 完全透明时，可以将音符移出场景
          meshRef.current.visible = false;
        }
      }
    } else {
      // 根据音符到达判定线的接近程度改变亮度
      const distanceToHitLine = Math.abs(zPosition);
      
      if (materialRef.current) {
        if (distanceToHitLine < 3) {
          // 接近判定线时增加亮度
          materialRef.current.emissiveIntensity = THREE.MathUtils.lerp(
            materialRef.current.emissiveIntensity,
            2.0,
            0.1
          );
        } else {
          // 远离判定线时降低亮度
          materialRef.current.emissiveIntensity = THREE.MathUtils.lerp(
            materialRef.current.emissiveIntensity,
            0.5,
            0.05
          );
        }
      }
    }
  });
  
  return (
    <group>
      {/* 音符主体 */}
      <mesh 
        ref={meshRef}
        position={[xPosition, 0.3, -50]} // 初始位置在远处
        castShadow
      >
        {isLongNote ? (
          <boxGeometry args={[noteWidth, 0.4, noteLength]} />
        ) : (
          <sphereGeometry args={[0.5, 32, 32]} />
        )}
        
        <meshStandardMaterial
          ref={materialRef}
          color={color}
          emissive={color}
          emissiveIntensity={0.5}
          metalness={0.9}
          roughness={0.1}
          transparent
          opacity={1.0}
        />
        
        {/* 音符光晕 */}
        <pointLight
          color={color}
          intensity={1}
          distance={2}
          decay={2}
        />
      </mesh>
    </group>
  );
};

export default Note; 